<template>
  <div class="tag-select-wrapper flex-x">
    <el-select
      v-model="selectedIds"
      multiple
      clearable
      placeholder="请选择标签"
      size="small"
      :disabled="false"
      @focus="handleFocus"      
      :popper-class="'hidden'"      
      @click.native.prevent
      @change="handleChange"
    >
      <el-option
        v-for="tag in selectedTags"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
        @click.native.stop.prevent
      />
    </el-select>
    <el-badge v-if="selectedIds.length > 0" :value="selectedIds.length" >      
    </el-badge>

    <tag-select-dialog
      v-model="selectedIds"
      ref="tagDialog"
      @change="handleChange"
    />
  </div>
</template>

<script>
import TagSelectDialog from './TagSelectDialog.vue'

export default {
  name: 'TagSelect',
  components: {
    TagSelectDialog
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },   
  },
  data() {
    return {
      selectedIds: [],
      selectedTags: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selectedIds = val
      }
    }
  },
  methods: {
    handleFocus() {
      // 当 select 获得焦点时，打开对话框而不是下拉菜单
      this.$refs.tagDialog.open(this.selectedIds)
    },
    handleChange(tagIds, tags) {
      if(tags) { 
        // 存在tags参数，说明是dialog的change事件，否则就是select的清除事件
        this.selectedTags = [...tags]
      }
      this.$emit('input', tagIds)
      this.$emit('change', tagIds)
    },    
  }
}
</script>

<style scoped>
.tag-select-wrapper {
  width: 100%;
  cursor: pointer;
}

:deep(.hidden) {
  display: none !important;
}

:deep(.el-select__tags) {
  flex-wrap: nowrap !important;
  overflow-x: hidden;
  white-space: nowrap;
}

:deep(.el-select__tags-text) {
  display: inline-block;
  white-space: nowrap;
}
</style>
